package com.blb.dslock_demo.zk;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService {

    //zk客户端
    @Resource
    private CuratorFramework curatorFramework;

    @Resource
    private ProductMapper productMapper;

    @Override
    public void reduceStock(Long productId) throws Exception {
        //获得zk分布式锁
        InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/locks");
        try {
            //请求锁
            lock.acquire();
            //查询库存
            Product product = productMapper.selectById(productId);
            if(product.getStock() > 0){
                //扣库存
                product.setStock(product.getStock() - 1);
                productMapper.updateById(product);
                System.out.println("扣库存成功");
            }else {
                System.out.println("库存不足");
            }
        } finally {
            //释放锁
            lock.release();
        }
    }
}
